/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package travelingsalesman;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

/**
 *
 * @author Rex Boris
 * @author DiAWAY
 */
public class CitiesFromFileReader {

    public String DataLocation = ".\\data\\";

    public static enum STATE {

        NODE_COORD_SECTION("NODE_COORD_SECTION"),
        EOF("EOF");
        private final String stateName;

        STATE(String name) {
            this.stateName = name;
        }
    }

    public CitiesFromFileReader() {
    }

    public double[][] getDat(String fileurl) throws NullPointerException, FileNotFoundException, IOException {
        File file = new File(fileurl);
        BufferedReader br = null;
        String str = "";

        br = new BufferedReader(new FileReader(file));
        while (br.ready()) {
            str += br.readLine() + " ";
        }
        br.close();

        ArrayList<Double> data = new ArrayList<Double>();
        StringTokenizer st = new StringTokenizer(str, " ");

        String token;
        boolean read = false; // is set true when STATE.NODE_COORD_SECTION is true, is set false when EOF is reached
        while (st.hasMoreTokens()) {
            token = st.nextToken().trim();
            if (token.equals(STATE.NODE_COORD_SECTION.toString())) {
                read = true;
                if (st.hasMoreTokens()) {
                    token = st.nextToken().trim(); // move to the next token, if possible.
                }
            }
            if (token.equals(STATE.EOF.toString())) {
                read = false;
            }
            if (read && token != null && !token.trim().equals("")) {
                data.add(Double.parseDouble(token));
            }
        }
        double[][] coordinates = new double[data.size()/3][2]; // Magic! size "will" (read: should) always be 3^n ;D
        int index = 0;
        for (int i = 0; i <= data.size()-3; i += 3) {
            coordinates[index][1] = data.get(i + 1);
            coordinates[index][0] = data.get(i + 2);
            index++;
        }
        return coordinates;
    }
}
